package com.cw.jeeyt.controller.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.security.SecurityOrgBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.security.SecurityOrgService;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 组织机构表控制层
 *
  * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/securityOrg")
public class SecurityOrgController extends BaseController {
    @Resource
    private SecurityOrgService securityOrgService;

    /**
     * 跳转到组织机构表列表查询页面
     *
     * @param returnMethod
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-selectParentOrg")
    public ModelAndView toSelectParentOrg(String selectType, String returnMethod) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityOrg_select");
        mv.addObject("selectType", selectType);
        mv.addObject("returnMethod", returnMethod);
        mv.addObject("PageDict",new PageDictDirective());
        return mv;
    }

    /**
     * 跳转到组织机构表列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {
        ModelAndView mv = new ModelAndView("security/securityOrg_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 跳转到组织机构表列表查询页面
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-orgTab")
    public ModelAndView toOrgTab(String orgId) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityOrgUser_tab");
        mv.addObject("orgId", orgId);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSecurityOrg")
    public ResultData listSecurityOrg(@RequestBody DataTable dataTable) throws Exception {

        SecurityOrgBo securityOrgBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SecurityOrgBo.class);
        if (securityOrgBo == null) {
            securityOrgBo = new SecurityOrgBo();
        }
        PageInfo<SecurityOrgBo> pageInfo = securityOrgService.queryByPage(securityOrgBo, dataTable.getStart(),
            dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到组织机构表表单页面
     *
     * @param orgId 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(String orgId, String operation, String openType) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityOrg_form");
        SecurityOrgBo securityOrgBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            securityOrgBo = new SecurityOrgBo();
        } else {
            securityOrgBo = securityOrgService.getSecurityOrgById(Long.parseLong(orgId));
        }
        mv.addObject("securityOrg", securityOrgBo);
        mv.addObject("openType", openType);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存组织机构表数据
     *
     * @param securityOrgBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveSecurityOrg", method = RequestMethod.POST)
    public JsonResultDto saveSecurityOrg(SecurityOrgBo securityOrgBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                securityOrgService.insert(securityOrgBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                securityOrgService.update(securityOrgBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除组织机构表
     *
     * @param securityOrgBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(SecurityOrgBo securityOrgBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityOrgService.delete(securityOrgBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return JSON.toJSONString(jsonResultDto);
    }

    /**
     * 根据操作类型保存系统菜单表数据
     *
     * @param orgId
     * @param orgParentId add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updateMenuParentId", method = RequestMethod.POST)
    public JsonResultDto updateSystemMenu(Long orgId, Long orgParentId) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityOrgService.updateOrgParentId(orgId, orgParentId);
            jsonResultDto.setMsg("更新成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("更新失败:" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 更新组织机构名称
     *
     * @param orgName 组织机构名称
     * @param orgId 组织机构Id
     * @throws Exception
     */
    @RequestMapping(value = "/updateOrgName")
    @ResponseBody
    public JsonResultDto updateMenuName(Long orgId, String orgName) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            securityOrgService.updateOrgName(orgId, orgName);
            jsonResultDto.setSuccess(true);
            jsonResultDto.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("更新失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 跳转到自动生成代码配置页面
     *
     * @param menuId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/org_tree")
    public ModelAndView orgTree(String menuId) throws Exception {

        ModelAndView mv = new ModelAndView("security/securityOrg_tree");
        //加载根节点菜单信息
        SecurityOrgBo securityOrgBo = securityOrgService.queryRootSecurityOrg();
        String nodesJson = "";
        if (securityOrgBo != null) {
            nodesJson = securityOrgService.queryOrgJson(securityOrgBo.getOrgId(), true, false);
        }
        if (!StringUtils.isEmpty(nodesJson)) {
            nodesJson = nodesJson.replace("\"", "'");
        }
        mv.addObject("nodesJson", nodesJson);
        return mv;
    }

    /**
     * 根据节点id加载叶子节点
     *
     * @param orgParentId
     * @return
     */
    @ResponseBody
    @RequestMapping("/getNodesDataById")
    public String getNodesDataById(Long orgParentId) throws Exception {

        StringBuffer nodesJson = new StringBuffer("");
        List<SecurityOrgBo> securityOrgList = securityOrgService.querySecurityOrgListByParentId(orgParentId);
        if (securityOrgList != null && !securityOrgList.isEmpty()) {
            nodesJson.append("[");
            int i = 0;
            for (SecurityOrgBo securityOrg : securityOrgList) {
                if (i == 0) {
                    nodesJson.append(
                        "{id:'" + securityOrg.getOrgId() + "', pId:'" + securityOrg.getOrgParentId() + "', name: '"
                            + securityOrg.getOrgName() + "',open:false}");
                } else {
                    nodesJson.append(
                        ",{id:'" + securityOrg.getOrgId() + "', pId:'" + securityOrg.getOrgParentId() + "', name: '"
                            + securityOrg.getOrgName() + "',open:false}");
                }
                i++;
            }
            nodesJson.append("]");
        } else {
            nodesJson.append("[]");// 其他情况：父节点没有子节点
        }
        return nodesJson.toString();
    }
}
